<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户详情</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card shadow="never" :body-style="{ padding: '5px' }">
      <div class="list">
        <el-row>
          <el-col :span="4">
            <div>
              <el-input v-model="searchParam" class="search-input" placeholder="请输入手机号或姓名"></el-input>
            </div>
          </el-col>
          <el-col :span="2">
            <div>
              <el-button @click="search" type="primary" icon="el-icon-search">搜索</el-button>
            </div>
          </el-col>

          <el-col :span="2">
            <div class="add">
              <el-button @click="toOpenAddDialog()" type="primary">
                <i class="el-icon-user"></i>
                添加
              </el-button>
            </div>
          </el-col>
          <el-col :span="3">
            <div class="batchdelete">
              <el-button @click="batchDelete" type="danger">批量删除</el-button>
            </div>
          </el-col>
          <el-col :span="13">
            <el-tooltip content="点击刷新" placement="top" effect="dark">
              <el-button
                @click="refreshTable"
                class="refresh"
                type="success"
                icon="el-icon-refresh"
                circle
              ></el-button>
            </el-tooltip>
          </el-col>
        </el-row>

        <el-table
          highlight-current-row
          :data="managerList"
          stripe
          border
          style="width: 1100px "
          header-align="center"
          @selection-change="handleSelectionChange"
        >
          >
          <el-table-column :selectable="selectInit" fixed type="selection" width="40"></el-table-column>
          <el-table-column resizable align="center" label="登录名" width="130px">
            <template slot-scope="scope">
              <el-popover trigger="hover" placement="top">
                <p>用户id: {{ scope.row.mgId }}</p>
                <p>管理员姓名: {{ scope.row.realName }}</p>
                <p>手机号: {{ scope.row.mgMobile }}</p>
                <p>邮箱: {{ scope.row.mgEmail }}</p>
                <p>角色: {{ scope.row.roleName }}</p>
                <p>新增时间: {{ scope.row.gmtCreate }}</p>
                <div slot="reference" class="name-wrapper">
                  <el-tag size="medium">{{ scope.row.mgName }}</el-tag>
                </div>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column sortable prop="mgMobile" label="手机号" width="115"></el-table-column>
          <el-table-column
            resizable
            align="center"
            prop="mgEmail"
            sortable
            label="邮箱"
            width="180px"
          ></el-table-column>
          <el-table-column resizable sortable align="left" prop="roleName" label="角色" width="130px">
            <template slot-scope="scope">
              <i class="el-icon-user"></i>
              <span>{{ scope.row.roleName }}</span>
            </template>
          </el-table-column>
          <el-table-column sortable label="添加时间" width="195">
            <template slot-scope="scope">
              <i class="el-icon-time"></i>
              <span style="margin-left: 10px">{{ scope.row.gmtCreate }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" sortable prop="mgState" label="状态" width="80">
            <template slot-scope="scope">
              <el-switch
                :disabled="scope.row.roleLevel== 0 ? true : false "
                v-model="scope.row.mgState"
                @change="changeStatus(scope.row)"
                active-color="#13ce66"
                inactive-color="#ff4949"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column align="center" fixed="right" label="操作" width="255 px">
            <template slot-scope="scope">
              <el-tooltip placement="top" class="item" effect="dark" content="密码重置">
                <el-button
                  :disabled="scope.row.roleLevel== 0 ? true : false "
                  size="mini"
                  type="info"
                  @click="resetPwd(scope.row)"
                >
                  <i class="el-icon-refresh-right"></i>
                </el-button>
              </el-tooltip>

              <el-tooltip placement="top" class="item" effect="dark" content="更换角色">
                <el-button
                  :disabled="scope.row.roleLevel== 0 ? true : false "
                  size="mini"
                  type="primary"
                  @click="handleRoleEdit(scope.$index, scope.row)"
                >
                  <i class="el-icon-setting"></i>
                </el-button>
              </el-tooltip>

              <el-button
                :disabled="scope.row.roleLevel== 0 ? true : false "
                size="mini"
                type="success"
                @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button>

              <el-popconfirm
                @confirm="isconfirm( scope.row)"
                confirm-button-text="我意已决"
                cancel-button-text="点错了"
                icon="el-icon-info"
                icon-color="red"
                title="确定要删除吗"
              >
                <el-button
                  :disabled="scope.row.roleLevel== 0 ? true : false "
                  slot="reference"
                  size="mini"
                  type="danger"
                >删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 40, 80]"
          :page-size="limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </el-card>
    <!-- 用户修改对话框 -->

    <div class="dialog-form">
      <el-dialog
        @close="closeDialog"
        title="资料修改"
        :visible="dialogFormVisible"
        width="35%"
        :before-close="handleClose"
      >
        <el-form
          :rules="rules"
          ref="ruleForm"
          label-position="right"
          :model="managerForm"
          label-width="100px"
        >
          <el-form-item label="用户id">
            <el-input
              :disabled="true"
              v-model="managerForm.mgId"
              class="form-input"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item prop="mgName" label="登录名">
            <el-input clearable v-model="managerForm.mgName" class="form-input" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item prop="realName" label="管理员姓名">
            <el-input
              clearable
              v-model="managerForm.realName"
              class="form-input"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item prop="mgMobile" label="手机号">
            <el-input
              clearable
              v-model="managerForm.mgMobile"
              class="form-input"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item prop="mgEmail" label="邮箱">
            <el-input clearable v-model="managerForm.mgEmail" class="form-input" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="updateStatistic('ruleForm')">确 定</el-button>
          <el-button @click="dialogFormVisible = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>

    <!-- 修改权限信息 -->
    <div class="dialog-form">
      <el-dialog
        @close="closePermissionDialog"
        title="修改权限"
        :visible="dialogRoleView"
        width="35%"
        :before-close="handleBeforeClosePermissionDialog"
      >
        <el-form
          :rules="rules"
          ref="ruleFormRef"
          label-position="right"
          :model="roleForm"
          label-width="80px"
        >
          <el-form-item label="用户名">
            <el-input
              :disabled="true"
              v-model="roleForm.mgName"
              class="form-input"
              autocomplete="off"
            ></el-input>
          </el-form-item>

          <el-form-item prop="roleId" label="角色">
            <el-select v-model="roleForm.roleId" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="updateRoleSelect('ruleFormRef')">确 定</el-button>
          <el-button @click="dialogRoleView = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>
    <!-- 用户新增 -->
    <div class="dialog-form">
      <el-dialog
        modal
        top="20px"
        @close="closeDialog"
        title="用户新增"
        :visible="addDialogVisible"
        width="35%"
        :before-close="handleClose"
      >
        <el-form
          label-position="right"
          :rules="rules"
          ref="addFormRef"
          :model="managerForm"
          label-width="80px"
        >
          <el-form-item prop="mgName" label="登录名">
            <el-input clearable v-model="managerForm.mgName" class="form-input" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item prop="mgPwd" label="密码">
            <el-input clearable v-model="managerForm.mgPwd" class="form-input" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item prop="realName" label="姓名">
            <el-input
              clearable
              v-model="managerForm.realName"
              class="form-input"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item prop="mgMobile" label="手机号">
            <el-input
              clearable
              v-model="managerForm.mgMobile"
              class="form-input"
              autocomplete="off"
            ></el-input>
          </el-form-item>
          <el-form-item prop="mgEmail" label="邮箱">
            <el-input clearable v-model="managerForm.mgEmail" class="form-input" autocomplete="off"></el-input>
          </el-form-item>

          <el-form-item prop="roleId" label="角色">
            <el-select filterable clearable v-model="managerForm.roleId" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item prop="mgState" label="是否启用">
            <el-switch
              v-model="managerForm.mgState"
              active-color="#13ce66"
              inactive-color="#ff4949"
            ></el-switch>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="addManagerForm('addFormRef')">确 定</el-button>
          <el-button @click="addDialogVisible = false">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  inject: ["reload"],
  name: "ManagerList",
  data() {
    return {
      managerList: [
        {
          userId: "",
          username: "",
          phone: "",
          avatar: "",
          permission: "",
          gmtCreate: "",
          gmtModified: "",
          mgState: true,
          roleLevel: 1
        }
      ], //总记录数
      currentPage: 1, //当前页
      limit: 10, //每页显示多少条
      total: 100, //总条数
      date: "",
      startTime: "",
      endTime: "",
      searchParam: "",

      dialogFormVisible: false,
      addDialogVisible: false,
      dialogRoleView: false,
      managerForm: {
        mgState: true
      },
      formLabelWidth: "100px",
      multipleSelection: [],
      rules: {
        mgMobile: [
          {
            type: "number",
            required: true,
            validator: this.validatePhone,
            trigger: "blur"
          }
        ],
        mgEmail: [
          {
            type: "email",
            required: true,
            message: "邮箱格式不对哦",
            trigger: "blur"
          }
        ],
        realName: [
          {
            required: true,
            message: "姓名不能为空",
            trigger: "blur"
          }
        ],
        mgName: [
          {
            required: true,
            message: "登录名不能为空",
            trigger: "blur"
          }
        ],
        realName: [
          {
            required: true,
            message: "姓名不能为空",
            trigger: "blur"
          }
        ],
        mgPwd: [
          {
            required: true,
            validator: this.validatePwd,
            trigger: "blur"
          }
        ],
        roleId: [{ required: true, message: "请选择角色", trigger: "blur" }],
        roleLevel: [{ required: true, message: "请选择角色", trigger: "blur" }]
      },

      options: [
        {
          roleId: "选项1",
          roleName: "黄金糕"
        }
      ],
      roleForm: {
        roleId: "",
        mgName: "",
        managerId: ""
      }
    };
  },
  methods: {
    resetPwd(row) {
      const params = new URLSearchParams();
      params.append("mgId", row.mgId);
      this.$http
        .put("/manager/resetPassword", params)
        .then(resp => {
          let { code, msg } = resp.data;
          if (code === 1) {
            return this.$message.success(msg);
          }
          return this.$message.error(msg);
        })
        .catch(resp => {});
    },
    updateRoleSelect(ruleFormRef) {
      this.$refs[ruleFormRef].validate(valid => {
        if (valid) {
          this.$http
            .post("/manager/manager-role/addRolePermission", this.roleForm)
            .then(resp => {
              let { code, msg } = resp.data;
              if (code === 1) {
                this.dialogRoleView = false;
                this.$message.success("添加成功");
                return this.reloadTable();
              }
              return this.$message.error(msg);
            })
            .catch(resp => {});
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    //复选框
    selectInit(row, index) {
      if (row.roleLevel == 0) {
        return false; //不可勾选
      } else {
        return true; //可勾选
      }
    },
    batchDelete() {
      let ids = [];
      this.multipleSelection.forEach(element => {
        ids.push(element.mgId);
      });

      this.$http
        .delete("/manager/batchDelete", {
          params: {
            ids: ids.toString()
          }
        })
        .then(resp => {
          let { code, msg } = resp.data;
          if (code === 1) {
            this.$message.success("批量删除成功");
            return this.reloadTable();
          }
          return this.$message.error(msg);
        })
        .catch(resp => {});
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    toOpenAddDialog() {
      this.managerForm = { mgState: true };
      this.$http
        .get("/manager/role/noAuthorize/queryRoleListInfo")
        .then(resp => {
          let { msg, code } = resp.data;
          let { roleSelectVOList } = resp.data.data;
          if (code === 1) {
            this.options = roleSelectVOList;
          }
        })
        .catch(resp => {});
      this.addDialogVisible = true;
    },
    addManagerForm(addFormRef) {
      console.log(this.managerForm);
      this.$refs[addFormRef].validate(valid => {
        if (valid) {
          this.$http
            .post("/manager/addManager", this.managerForm)
            .then(resp => {
              let { code, msg } = resp.data;
              if (code === 1) {
                this.addDialogVisible = false;
                return this.$message.success("添加成功");
              }
              return this.$message.error(msg);
            })
            .catch(resp => {});
        }
      });
    },
    handleEdit(index, row) {
      this.managerForm = row;
      this.dialogFormVisible = true;
    },
    handleRoleEdit(index, row) {
      this.roleForm.roleId = row.roleName;
      this.roleForm.mgName = row.mgName;
      this.roleForm.managerId = row.mgId;
      this.$http
        .get("/manager/role/noAuthorize/queryRoleListInfo")
        .then(resp => {
          let { msg, code } = resp.data;
          let { roleSelectVOList } = resp.data.data;
          if (code === 1) {
            this.options = roleSelectVOList;
            this.roleForm.mgId = row.mgId;
          }
          this.dialogRoleView = true;
        })
        .catch(resp => {});
    },

    isconfirm(row) {
      this.$http
        .delete("/manager/deleteById/", {
          params: {
            managerId: row.mgId
          }
        })
        .then(resp => {
          let code = resp.data.code;
          if (code === 1) {
            this.$message({
              showClose: true,
              message: "删除成功！",
              type: "success"
            });
            this.reload();
          } else {
            return this.$message({
              showClose: true,
              message: resp.data.msg,
              type: "warning"
            });
          }
        })
        .catch(resp => {
          console.log(resp);
        });
    },

    handleSizeChange(val) {
      this.limit = val;
      this.getManagerList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getManagerList();
    },
    search() {
      let startDate = this.date.toString();
      if (startDate) {
        this.startTime = startDate.substring(0, 19);
        this.endTime = startDate.substring(20);
      }
      this.$http
        .get("/manager/queryManagerByCondition", {
          params: {
            page: this.currentPage,
            limit: this.limit,
            startTime: this.startTime,
            endTime: this.endTime,
            searchParam: this.searchParam
          }
        })
        .then(resp => {
          let data = resp.data;

          if (data.code === 1) {
            this.managerList = data.data.managerVoList;
            this.total = parseInt(data.data.total);
            return;
          }
          this.$message.warning("数据为空");
        })
        .catch(resp => {});
    },
    getManagerList() {
      this.$http
        .get("/manager/queryManagerByCondition", {
          params: {
            page: this.currentPage,
            limit: this.limit
          }
        })
        .then(resp => {
          let data = resp.data;
          if (data.code === 1) {
            this.managerList = data.data.managerVoList;
            this.total = parseInt(data.data.total);
            return;
          }
          return this.$notify.info({
            title: "tips",
            message: "数据为空"
          });
        })
        .catch(resp => {});
    },
    reloadTable() {
      this.$http
        .get("/manager/queryManagerByCondition", {
          params: {
            page: 1,
            limit: 5
          }
        })
        .then(resp => {
          let data = resp.data;
          if (data.code === 1) {
            this.managerList = data.data.managerVoList;
            this.total = parseInt(data.data.total);
            return;
          }
        })
        .catch(resp => {});
    },
    changeStatus(row) {
      let params = new URLSearchParams();
      params.append("status", row.mgState);
      params.append("managerId", row.mgId);
      this.$http
        .put("/manager/updateStatus/", params)
        .then(resp => {
          let code = resp.data.code;
          let flag = resp.data.data.status;
          if (code === 1) {
            if (flag) {
              return this.$message.success("已启用");
            }
            return this.$message.info("已停用");
          }
          return this.$message.error(resp.data.msg);
        })
        .catch(resp => {
          console.log(resp);
        });
    },
    refreshTable() {
      this.reload();
      this.$message.success("已刷新");
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(resp => {
          this.getManagerList();
          this.dialogFormVisible = false;
          this.addDialogVisible = false;
          done();
        })
        .catch(resp => {
          this.reloadTable();
        });
    },
    handleBeforeClosePermissionDialog(done) {
      this.$confirm("确认关闭？")
        .then(resp => {
          // this.getManagerList();
          this.dialogRoleView = false;
          done();
        })
        .catch(resp => {
          this.reloadTable();
        });
    },
    closeDialog() {
      this.getManagerList();
    },
    closePermissionDialog() {
      this.dialogRoleView = false;
    },
    updateStatistic(ruleForm) {
      this.$refs[ruleForm].validate(valid => {
        if (valid) {
          this.$http
            .put("/manager/updateManagerStatistics", this.managerForm)
            .then(resp => {
              let code = resp.data.code;
              if (code === 1) {
                this.$message.success("修改成功");
                return (this.dialogFormVisible = false);
              }
              return this.$message.error(resp.data.msg);
            })
            .catch(resp => {
              // console.log(resp);
            });
        } else {
          this.$message.warning("信息不完整");
          return false;
        }
      });
    },
    // 自定义校验规则
    validatePhone(rule, value, callback) {
      const reg = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (reg.test(value)) {
        return callback();
      }
      callback(new Error("请输入合法的手机号"));
    },
    validatePwd(rule, value, callback) {
      const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{5,16}$/;
      if (reg.test(value)) {
        return callback();
      }
      callback(new Error("5-16位，密码要包含数字和字母"));
    }
  },
  created() {
    this.getManagerList();
  }
};
</script>

<style scoped>
.el-input {
  width: 150px;
  margin-right: 10px;
}
.main-up {
  float: left;
}

.search-input {
  width: 160px;
}
.list {
  margin-top: 25px;
  margin-left: 20px;
}
.el-row {
  margin-top: 10px;
  margin-bottom: 10px;
}
.refresh {
  float: right;
  margin-right: 20px;
}
.el-pagination {
  margin-top: 10px;
}
.form-input {
  width: 200px;
}
.el-form {
  margin-left: 30px;
}
.el-card {
  margin-top: 20px;
}
.el-breadcrumb {
  margin-top: 10px;
}
.search {
  margin-left: 20px;
}
.add {
  margin-left: 20px;
}
.el-select {
  width: 200px;
}

.dialog-form {
  margin-top: 20px;
}
.batchdelete {
  margin-left: 38px;
}
</style>